import apiClient from './auth';

// 获取价格方案列表
export const getPricingPlans = async () => {
  try {
    const response = await apiClient.get('/subscriptions/pricing-plans/');
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 获取当前用户的订阅信息
export const getCurrentSubscription = async () => {
  try {
    const response = await apiClient.get('/subscriptions/subscriptions/current/');
    return response.data;
  } catch (error) {
    if (error.response && error.response.status === 404) {
      return null; // 用户没有活跃订阅
    }
    throw error.response ? error.response.data : error;
  }
};

// 创建新订阅
export const createSubscription = async (subscriptionData) => {
  try {
    const response = await apiClient.post('/subscriptions/subscriptions/', {
      membership_type: subscriptionData.pricing_plan,
      auto_renew: subscriptionData.auto_renew || true
    });
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 取消自动续订
export const cancelAutoRenew = async (subscriptionId) => {
  try {
    const response = await apiClient.post(`/subscriptions/subscriptions/${subscriptionId}/cancel_auto_renew/`);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 创建支付记录
export const createPayment = async (paymentData) => {
  try {
    const response = await apiClient.post('/subscriptions/payments/', paymentData);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 处理支付（模拟支付成功）
export const processPayment = async (paymentId) => {
  try {
    const response = await apiClient.post(`/subscriptions/payments/${paymentId}/process_payment/`);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 获取用户的支付历史
export const getPaymentHistory = async () => {
  try {
    const response = await apiClient.get('/subscriptions/payments/');
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};